import router from '@/router'
import nprogress from 'nprogress'
import setting from './setting'
import 'nprogress/nprogress.css'
import useUserStore from './store/modules/user'
import pinia from './store'
nprogress.configure({ showSpinner: false })
const userStore = useUserStore(pinia)
console.log(userStore)
// console.log(userStore)
router.beforeEach(async (to, from, next) => {
  document.title = setting.title + '-' + to.meta.title
  nprogress.start()
  const token = userStore.token
  const username = userStore.username
  if (token) {
    if (to.path == '/login') {
      next({ path: '/' })
    } else {
      if (username) {
        next()
      } else {
        try {
          await userStore.userInfo()
          next()
        } catch (err) {
          console.log(err)
          await userStore.userLogout()
          next({ path: '/login', query: { redirect: to.path } })
        }
      }
    }
  } else {
    if (to.path == '/login') {
      next()
    } else {
      next({ path: '/login', query: { redirect: to.path } })
    }
  }
})
router.afterEach((to, from) => {
  nprogress.done()
})
